package com.sunday.common.mq.kafka.study.spring.e6_Receiving_Messages_4_Batch_Manual_Ack;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.Consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.SendResult;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws ExecutionException, InterruptedException {
        CompletableFuture<SendResult<Object, Object>> future;
        future = kafkaTemplate.send(topic, key, key);
        log.info("{}", future.get());
    }

    @GetMapping("/batch/{topic}")
    public void batch(@PathVariable String topic) {
        CompletableFuture<SendResult<Object, Object>> future;
        for (int i = 0; i < 10; i++) {
            future = kafkaTemplate.send(topic, i + "", i + "");
            future.whenComplete((result, throwable) -> log.info("[{}] result : {}, throwable : {}", topic, result, throwable));
        }
    }

    @KafkaListener(
            id = "myId_3",
            topics = "topic3",
            clientIdPrefix = "TEST3",
            batch = "true",
            containerFactory = "kafkaBatchListenerContainerFactory"
    )
    /**
     * https://docs.spring.io/spring-kafka/docs/current/reference/html/#batch-listeners
     * 一定注意
     * 您可以在每条消息中接收具有每个偏移量和其他详细信息的对象，
     * 但它必须是在方法上定义的唯一参数（使用手动提交时，可选参数和/或参数除外）。
     * 以下示例演示如何执行此操作：ListMessage<?> AcknowledgmentConsumer<?, ?>
     */
    public void listen(
            List<Message<?>> list,
            Acknowledgment ack,
            Consumer<?, ?> consumer
    ) {
        log.info("[data] ======= {}", list.size());
//        list.stream().forEach(s -> log.info("{}", s));
//        log.info("[ack] ======= {}", ack);
//        log.info("[consumer] ======= {}", consumer);
        ack.acknowledge();
    }

}
